//
//  ViewController.m
//  27-QQMusic-play
//
//  Created by 曹曹 on 16/8/19.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayView.h"
#import "GX_Button.h"
#import "UIImage+GX.h"

@interface ViewController ()
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) AVPlayer *player;
@property (weak, nonatomic) IBOutlet PlayView *playView;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (weak, nonatomic) IBOutlet UILabel *leftTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *rigtTimeLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIImageView *songImage;
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImage;
@property (nonatomic, strong) NSMutableArray<AVPlayerItem *> *playItems;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSongView];
    [self initLocalAudioPlayer];
//    [self initAVPlayer];
    [self setPlayView];
    AVPlayer *play = [[AVPlayer alloc] init];
    play = nil;
}

- (void)handleData {
    self.playItems = [NSMutableArray array];
    AVPlayerItem *one = [self playerItemWithResource:@"03 Hymn For The Weekend" type:@"m4a"];
    AVPlayerItem *two = [self playerItemWithResource:@"Maroon 5 - Sugar" type:@"mp3"];
    AVPlayerItem *thr = [self playerItemWithResource:@"everglow" type:@"mp3"];
    [_playItems addObject:one];
    [_playItems addObject:two];
    [_playItems addObject:thr];
}

- (AVPlayerItem *)playerItemWithResource:(NSString *)resource type:(NSString *)type {
    NSString *path = [[NSBundle mainBundle] pathForResource:resource ofType:type];
    NSURL *url = [NSURL fileURLWithPath:path];
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
    return item;
}

- (void)configSongView {
    self.songImage.image = [[UIImage imageNamed:@"song"] circleImageWithBorderWidth:10 borderColor:[UIColor blackColor]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back"]];
    
    
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc]initWithEffect:effect];
    visualView.frame = [[UIScreen mainScreen] bounds];
    [self.backgroundImage addSubview:visualView];
    visualView.alpha = 0.9;
}

- (void)initAnimatiom {
    //创建一个绕z轴旋转的动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转一周
    animation.toValue = @(2 * M_PI);
    //循环次数，尽量大
    animation.repeatCount = MAXFLOAT;
    //执行一次动画需要的时间
    animation.duration = 70.0f;
    [self.songImage.layer addAnimation:animation forKey:@"rotationAnimation"];
}

- (void)pauseLayer:(CALayer*)layer {
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

- (void)resumeLayer:(CALayer*)layer {
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}


- (void)initLocalAudioPlayer {
    NSArray *array = @[@"everglow", @"RSP", @"Maroon 5 - Sugar"];
    NSURL *url = [self audioURLWithResource:array.firstObject];
    NSError *error = nil;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    [self configProgressView];
}

- (NSURL *)audioURLWithResource:(NSString *)resource {
    NSString *path = [[NSBundle mainBundle] pathForResource:resource ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    return url;
}

- (void)initAVPlayer {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"everglow" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [AVPlayer playerWithURL:url];
    [self configProgressView];
}

- (void)setPlayView {
    [self.playView play:^(GX_Button *play) {
        [self.audioPlayer play];
//        [self.player play];
        [self addTimer];
        CAAnimation * animation = [self.songImage.layer
                                   animationForKey:@"rotationAnimation"];
        if (animation == nil) {
            [self initAnimatiom];
        } else {
            [self resumeLayer:self.songImage.layer];
        }
    } pause:^(GX_Button *pause) {
        [self.audioPlayer pause];
//        [self.player pause];
        [self removeTimer];
        [self pauseLayer:self.songImage.layer];
    }];
    [self.playView last:^(GX_Button *last) {
        self.audioPlayer = nil;
    } next:^(GX_Button *next) {
        NSLog(@"next song");
    }];
}

- (void)configProgressView {
    NSString *timeString = [NSString stringWithFormat:@"%.2f", self.audioPlayer.duration / 60];
    [_slider setMaximumTrackImage:[UIImage imageNamed:@"player_slider_playback_right"] forState:UIControlStateNormal];
    [_slider setMinimumTrackImage:[UIImage imageNamed:@"player_slider_playback_left"] forState:UIControlStateNormal];
    [_slider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    _slider.maximumValue = self.audioPlayer.duration;
    [_slider addTarget:self action:@selector(changeProgress:) forControlEvents:UIControlEventValueChanged];
    _leftTimeLabel.text = @"00:00";
    _rigtTimeLabel.text = timeString;
}
// 使用slider改变播放进度
- (void)changeProgress:(UISlider *)slider {
    self.audioPlayer.currentTime = slider.value;
}
// slider随播放进度移动
- (void)changeSliderValue {
    CGFloat currentTime = self.audioPlayer.currentTime;
    self.slider.value = currentTime;
    _leftTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)currentTime / 60, (int)currentTime % 60];
//    CGFloat leftSeconds = self.audioPlayer.duration - currentTime;
//    _rigtTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d", (int)leftSeconds / 60, (int)leftSeconds % 60];
}

- (void)addTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2
                                                  target:self
                                                selector:@selector(changeSliderValue)
                                                userInfo:nil
                                                 repeats:YES];
}
- (void)removeTimer {
    [self.timer invalidate];
    _timer = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
